﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace RG.Common.WPF.Frames
{
    [SupportDataBinding]
    public class ActiveErrorBoxVM : INotifyPropertyChanged, IFirePropertyChanged 
    {
        [DependOn("ErrorCollector", "OutLineErrors")]
        public string Errors
        {
            get
            {
                var allErrors = new StringBuilder();
                if (ErrorCollector != null && !string.IsNullOrEmpty(ErrorCollector.ToString())) allErrors.Append(ErrorCollector.ToString());
                if (!string.IsNullOrEmpty(OutLineErrors)) allErrors.Append(OutLineErrors);
                return allErrors.ToString();
            }
        }

        public StringBuilder ErrorCollector { get; set; }

        public List<ValidationErrorMessage> Messages { get; set; }


        public bool HasErrors { get; set; }
        public string OutLineErrors { get; set; }

        public ActiveErrorBoxVM()
        {
            ErrorCollector = new StringBuilder();
            Messages = new List<ValidationErrorMessage>();
        }

        public void OnError(ValidationErrorMessage obj)
        {
            if (obj.HasError && Messages.FirstOrDefault(x => x.Sender == obj.Sender) == null &&
                !string.IsNullOrEmpty(obj.ErrorMessage))
                Messages.Add(obj);
            if (!obj.HasError)
            {
                var msg = Messages.FirstOrDefault(x => x.Sender == obj.Sender);
                if (msg != null) Messages.Remove(msg);
            }

            var ec = new StringBuilder();
            foreach (var e in Messages)//erCol)
                ec.AppendLine(!string.IsNullOrEmpty(e.ErrorMessage) ? e.ErrorMessage : "-----------");
            ErrorCollector = ec;
            HasErrors = ErrorCollector.ToString() != "";
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string name)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}
